/**
 * 集合所有的文件操作
 * */
class FileOperate{
  // 获取base64
  static getBase64(file){
    return new Promise((resolve,reject) => {
      const reader = new FileReader();///FileReader类就是专门用来读文件的
      reader.readAsDataURL(file);//readAsDataURL: dataurl它的本质就是图片的二进制数据， 进行base64加密后形成的一个字符串，
      reader.onload = () => resolve(reader.result);// 成功和失败返回对应的信息，reader.result一个base64，可以直接使用
      reader.onerror = error => reject(error); // 失败返回失败的信息
    });
  }
  // base64转为文本
  static base64ToText(base64){
    const decoded = atob(base64);
    const decoder = new TextDecoder();
    return decoder.decode(new Uint8Array(Array.from(decoded).map(c => c.charCodeAt(0))));
  }
  // base64转为blob
  static base64ToBlob(base64Data){
    let byteString = base64Data.split(',');
    const mimeString = byteString[0].match(/:(.*?);/)[1];
    byteString = atob(byteString[1]);
    let length = byteString.length;
    const ia = new Uint8Array(length);
    while(length >= -1){
      ia[length] = byteString.charCodeAt(length);
      length = length - 1;
    }
    return new Blob([ia],{type:mimeString});
  }
  // blob转为arraybuffer
  static blobToAb(blob){
    return new Promise((resolve,reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        resolve(reader.result);
      };
      reader.onerror = reject;
      reader.readAsArrayBuffer(blob);
    });
  }
  // -----------------单独的文件操作----------------------
  // 添加wav的头部
  static addWavHead(data){
    const buffer = new ArrayBuffer(Number('44') + data.byteLength);
    const view = new DataView(buffer);
    FileOperate._writeString(view,0,'RIFF');// RIFF 固定字符串
    view.setUint32(Number('4'),Number('36') + data.byteLength,true);// 录音数据长度+(44-8)
    FileOperate._writeString(view,Number('8'),'WAVE');// WAVE 固定字符串
    FileOperate._writeString(view,Number('12'),'fmt ');// "fmt " 固定字符串
    view.setUint32(Number('16'),Number('16'),true);// size1=16 固定值
    view.setUint16(Number('20'),1,true);// format tag=1 固定值
    view.setUint16(Number('22'),1,true);// chanel 声道数 1为单声道 2为双声道
    view.setUint32(Number('24'),Number('16000'),true);// sampleRate 采样率
    view.setUint32(Number('28'),Number('16000') * Number('2'),true); // byteRate 每秒所需字节数
    view.setUint16(Number('32'),Number('16000') * Number('2'),true);// blockAlign 每一个采样需要的字节数
    view.setUint16(Number('34'),Number('16'),true);// bitsPerSample 采样位宽
    FileOperate._writeString(view,Number('36'),'data');// subchunk2ID 固定值data
    view.setUint32(Number('40'),data.byteLength,true);// subchunk2Size 音频文件总长度 文件总长度-44
    const originData = new DataView(data);
    for(let index = 0; index < data.byteLength; index++){
      view.setUint8(Number('44') + index,originData.getUint8(index));
    }
    return buffer;
  }
  static _writeString(view,offset,str){
    for(let i = 0; i < str.length; i++){
      view.setUint8(offset + i,str.charCodeAt(i));
    }
  }
  // -----------------对图片的处理----------------
  static loadImage(src,option = {}){
    return new Promise((resolve,reject) => {
      const image = new Image();
      const {crossOrigin} = option;
      if(crossOrigin){
        image.crossOrigin = crossOrigin;
      }
      image.onload = () => {
        resolve(image);
      };
      image.onerror = e => {
        reject(e);
      };
      image.src = src;
    });
  }
  static getImageSize(src){
    return FileOperate.loadImage(src).then(image => ({
      width:image.naturalWidth,height:image.naturalHeight
    })).catch(err => {
      return err;
    });
  }
  // -----------------对视频的处理----------------
  static loadVideo(src,option = {}){
    return new Promise((resolve,reject) => {
      const video = document.createElement('video');
      const {crossOrigin} = option;
      if(crossOrigin){
        video.crossOrigin = crossOrigin;
      }
      video.onloadeddata = () => {
        resolve(video);
      };
      video.onerror = e => {
        reject(e);
      };
      video.src = src;
    });
  }
}

export default FileOperate
